package com.tc.dispatch.web.util;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

public class DateJsonValueProcessor implements JsonValueProcessor {
    private static final Log log = LogFactory.getLog(DateJsonValueProcessor.class);

    private String format = "yyyy-MM-dd";

    public String getFormat() {
        return format;
    }

    public void setFormat(String format) {
        this.format = format;
    }

    public Object processArrayValue(Object value, JsonConfig jsonConfig) {
        // log.debug("value: " + value);

        if (value == null) {
            return value;
        }

        Date[] dates = (Date[]) value;
        String[] resultValue = new String[dates.length];

        SimpleDateFormat sf = new SimpleDateFormat(format);
        for (int i = 0; i < dates.length; i++) {
            resultValue[i] = sf.format(dates[i]);
        }
        return resultValue;
    }

    public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
        // log.debug("key: " + key + "| value:" + value);

        if (value == null) {
            return value;
        }

        return new SimpleDateFormat(format).format((Date) value);
    }
}
